<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/9/27
 * Time: 10:21
 */

namespace app\back\controller;
require '../vendor/qiniu-php-sdk/autoload.php';
use Qiniu\Auth;
use app\common\model\File as FileModel;
use think\Session;


class System extends BaseController
{
    public function dashboard()
    {
        $session = Session::get();
        $this->assign('session_sum', count($session));
        return view();
    }

    public function upToken()
    {
        $user_id = Session::get('login.id');

        if(!isset($user_id))
        {
            return $this->redirect('back/User/login');
        }
        $bucket = config('qiniu_bucket_name');
        $accessKey = config('qiniu_access_key');
        $secretKey = config('qiniu_secret_key');
        $auth = new Auth($accessKey, $secretKey);
        $policy = array(
            'callbackUrl' => 'http://loear.com/admin/system/callback.html',
            'callbackBody' => '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)", "uid":' . $user_id . '}'
        );

        $upToken = $auth->uploadToken($bucket);
        return json(['uptoken'=>$upToken]);
    }

    public function callback()
    {
        $_body = file_get_contents('php://input');
        $body = json_decode($_body, true);
        $uid = $body['uid'];
        $fname = $body['fname'];
        $fkey = $body['fkey'];
        $desc = $body['desc'];
        $model = new FileModel();
        $data = [
            'uid'   =>  $uid,
            'fname' =>  $fname,
            'fkey'  =>  $fkey,
            'description'  =>  $desc,
        ];
        $model->save($data);

        if ($model->id)
            return json(['status' => 'success', 'code'  =>  '00000']);

        return json(['status' => 'failed', 'code'  =>  '99999']);
    }

    public function test()
    {
        /*$bucket = config('qiniu_bucket_name');
        $accessKey = config('qiniu_access_key');
        $secretKey = config('qiniu_secret_key');*/
        $upToken = $this->upToken();
        $this->assign(compact('upToken'));
        return view();
    }

    public function upload()
    {
        $upToken = $this->upToken();
        $this->assign(compact('upToken'));
        return view();
    }

    public function image()
    {
        return view();
    }

}